using OpenIddict.Abstractions;
using WL.Think.Abp.Dto;

namespace WL.Think.Abp.OpenIddict.Dtos;

public class ApplicationDto : BaseEntityDto
{
    /// <summary>
    /// 客户端ID
    /// </summary>
    public string? ClientId { get; set; }
    /// <summary>
    /// 显示名称
    /// </summary>
    public string? DisplayName { get; set; }
    /// <summary>
    /// 客户端类型
    /// </summary>
    public string? ClientType { get; set; }
    /// <summary>
    /// 客户端秘钥
    /// </summary>
    public string? ClientSecret { get; set; }
    /// <summary>
    /// 客户端地址
    /// </summary>
    public string? ClientUri { get; set; }
    /// <summary>
    /// Logo地址
    /// </summary>
    public string? LogoUri { get; set; }
    /// <summary>
    /// 同意类型
    /// </summary>
    public string? ConsentType { get; set; }
    /// <summary>
    /// 应用类型
    /// </summary>
    public string? ApplicationType { get; set; }
    /// <summary>
    /// 重定向地址
    /// </summary>
    public HashSet<string> RedirectUris { get; set; } = new HashSet<string>();
    /// <summary>
    /// 登出重定向地址
    /// </summary>
    public HashSet<string> PostLogoutRedirectUris { get; set; } = new HashSet<string>();
    /// <summary>
    /// 权限
    /// </summary>
    public HashSet<string> Permissions { get; set; } = new HashSet<string>(StringComparer.Ordinal);
    /// <summary>
    /// 范围
    /// </summary>
    public HashSet<string> Scopes => GetScopes();
    /// <summary>
    /// 授权类型
    /// </summary>
    public HashSet<string> GrantTypes => GetGrantTypes();

    private HashSet<string> GetScopes()
    {
        var scopes = new HashSet<string>();
        if(Permissions.Count > 0)
        {
            Permissions.Where(x=>x.StartsWith(OpenIddictConstants.Permissions.Prefixes.Scope, StringComparison.Ordinal))
                .ToList()
                .ForEach(x => scopes.Add(x.Substring(OpenIddictConstants.Permissions.Prefixes.Scope.Length)));
        }

        return scopes;
    }

    private HashSet<string> GetGrantTypes()
    {
        var grantTypes = new HashSet<string>();
        if (Permissions.Count > 0) {
            Permissions.Where(x => x.StartsWith(OpenIddictConstants.Permissions.Prefixes.GrantType, StringComparison.Ordinal))
                .ToList()
                .ForEach(x => grantTypes.Add(x.Substring(OpenIddictConstants.Permissions.Prefixes.GrantType.Length)));
        }
        return grantTypes;
    }
}
